<template>
  <div class="shopping container">
    <div class="shopping-header">
      <el-row type="flex" align="middle" justify="space-between" class="title">
        <div class="name">我的购物车({{ shoppingList.length }})</div>
        <el-link
          class="return"
          :underline="false"
          icon="edu-icon-chehui edu-icon--left"
          @click="handieReturn"
          >返回购物车</el-link
        >
      </el-row>
      <el-row type="flex" align="middle" class="navbar">
        <el-col :span="8" class="name">课程详情</el-col>
        <el-col :span="16" class="name">售价</el-col>
      </el-row>
    </div>
    <div class="shopping-list" v-if="shoppingList">
      <div class="shopping-mhm" v-for="(vo, index) in shoppingList" :key="index">
        <el-row type="flex" align="middle" class="mhm-header">
          <div class="title">{{ vo.school_name }}</div>
          <el-popover placement="bottom-start" trigger="hover" @show="getCouponSchoolInfo(vo)">
            <div v-loading="loading" class="shopping-coupon-loading">
              <el-scrollbar class="scrollbar">
                <div
                  class="shopping-coupon-popover"
                  v-for="(item, index) in couponSchoolList"
                  :key="index"
                >
                  <template v-if="item.useful == 1">
                    <el-row
                      type="flex"
                      align="middle"
                      class="item"
                      v-for="(crad, index) in item.list"
                      :key="index"
                    >
                      <div
                        class="card"
                        :class="[
                          crad.coupon_type == 1 ? 'youhui' : crad.coupon_type == 2 ? 'dazhe' : ''
                        ]"
                      >
                        <template v-if="crad.coupon_type == 1">
                          {{ crad.price | formatMoney }}
                        </template>
                        <template v-else-if="crad.coupon_type == 2">
                          {{ crad.discount | floatCount }}折
                        </template>
                      </div>
                      <div class="info">
                        <div class="name">
                          <template v-if="crad.coupon_type == 1">
                            满{{ crad.maxprice | floatCount }}减{{ crad.price | floatCount }}
                          </template>
                          仅限<span class="mhm">{{ crad.school_name }}</span
                          >使用
                        </div>
                        <div v-if="crad.use_etime" class="time">
                          {{ crad.use_stime | parseTime('{y}.{m}.{d}') }}-{{
                            crad.use_etime | parseTime('{y}.{m}.{d}')
                          }}
                        </div>
                        <div v-else class="time">永久有效</div>
                      </div>
                      <el-button
                        plain
                        size="mini"
                        @click="handieCouponChat(vo, crad)"
                        :disabled="vo.coupon_id == crad.id"
                        >{{ vo.coupon_id != crad.id ? '使用' : '已使用' }}</el-button
                      >
                    </el-row>
                  </template>
                </div>
              </el-scrollbar>
            </div>
            <div class="shopping-coupon-footer">
              <el-button plain @click="noCoupon(vo)" size="mini">不使用卡券</el-button>
            </div>
            <div slot="reference" v-if="!$util.isEmpty(vo.best_coupon)" class="coupon-title">
              <template v-if="vo.coupon_id === 0">
                使用优惠卷
              </template>
              <template v-else>
                <template v-if="vo.best_coupon.coupon_type == 1">
                  满{{ vo.best_coupon.maxprice | floatCount }}减{{
                    vo.best_coupon.price | floatCount
                  }}
                </template>
                <template v-else-if="vo.best_coupon.coupon_type == 2">
                  {{ vo.best_coupon.discount | floatCount }}折
                </template>
              </template>
              <i class="el-icon-arrow-down"></i>
            </div>
          </el-popover>
        </el-row>
        <div class="mhm-case">
          <el-row type="flex" class="item" v-for="(item, index) in vo.course_list" :key="index">
            <div class="img">
              <edu-image :src="item.cover_url" fit="cover"></edu-image>
            </div>
            <el-row type="flex" justify="space-between" class="info">
              <div class="name">{{ item.title }}</div>
              <el-row type="flex" class="dec">
                <span>课时数：{{ item.section_count }}节</span>
                <span v-if="item.term_time === 0">永久有效</span>
                <span v-else-if="('' + item.term_time).length < 5">
                  购买之日起<i>{{ item.term_time }}</i
                  >天内有效
                </span>
                <span v-else>{{ item.term_time | parseTime('有效期至：{y}-{m}-{d}') }}</span>
              </el-row>
            </el-row>
            <el-row class="end" type="flex" justify="end">
              <div class="picrie">
                <span v-if="isVip == 1">VIP价</span>
                {{ item.user_price | formatMoney }}
              </div>
            </el-row>
          </el-row>
        </div>
        <el-row type="flex" align="middle" justify="end" class="mhm-combined">
          <div class="discount">优惠：{{ vo.discount_price || 0 | formatMoney }}</div>
          <el-row type="flex" align="middle">
            <span class="name">合计：</span>
            <span class="money">{{ vo.discount_total_price || 0 | formatMoney }}</span>
          </el-row>
        </el-row>
      </div>
    </div>
    <!-- 积分抵扣 -->
    <Integral :credit_arr="creditList" :value="credit_price" @change="changePoints"></Integral>
    <el-divider></el-divider>
    <el-row type="flex" align="middle" justify="end" class="shopping-column">
      <el-row type="flex" align="middle">
        <div class="combined">
          <el-row type="flex" align="middle" justify="space-between">
            <span class="name">合计</span>
            <span class="money">{{ pay_price | formatMoney }}</span>
          </el-row>
          <el-row type="flex" align="middle" justify="space-between">
            <span class="name">优惠</span>
            <span class="discount"> -{{ reduced_price | formatMoney }}</span>
          </el-row>
        </div>
        <el-button type="primary" size="medium" @click="handiedingdan" :disabled="disabled"
          >提交订单</el-button
        >
      </el-row>
    </el-row>
  </div>
</template>

<script>
import projectSetting from '@/settings/projectSetting.js'
import { floatCount } from '@/utils/filters.js'
import Integral from './components/integral'
import { mapMutations } from 'vuex'
export default {
  components: {
    Integral
  },
  data() {
    return {
      checked: false,
      shoppingList: [],
      loading: false,
      couponSchoolList: [],
      disabled: false,
      creditList: [],
      credit_price: 0,
      credit_obj: {},
      pay_price: 0,
      reduced_price: 0
    }
  },
  created() {
    this.getPaymentInfo()
  },
  computed: {
    // 用户会员状态
    isVip() {
      return this.$store.getters['user/accountInfo'].is_vip
    }
  },
  methods: {
    ...mapMutations({
      changeOrderData: 'order/SET_ORDER_DATA'
    }),
    // 获取商品
    getPaymentInfo() {
      this.$api.getOrderCourseCart(
        {
          course_ids: this.$route.query.course_ids
        },
        res => {
          // 初始完成添加 checked 属性
          let data = res.data.cart
          data.forEach(item => {
            let buyPrice = 0
            if (!this.$util.isEmpty(item.best_coupon)) {
              this.$set(item, 'coupon_id', item.best_coupon.id)
              if (this.$util.isDef(item.best_coupon.ticket_id)) {
                this.$set(item, 'ticket_id', item.best_coupon.ticket_id)
              } else {
                this.$set(item, 'ticket_id', 0)
              }
              if (item.best_coupon.coupon_type == 1) {
                buyPrice = floatCount(item.best_coupon.price)
              } else if (item.best_coupon.coupon_type == 2) {
                let discount = item.best_coupon.discount // 折扣
                let price = item.total_price // 课程原价
                buyPrice = floatCount(price - price * (discount / 10)).toFixed(2) // 计算出优惠的价格
              }
              this.$set(item, 'discount_price', buyPrice)
            } else {
              this.$set(item, 'coupon_id', 0)
              this.$set(item, 'ticket_id', 0)
            }
            let pref = (item.total_price * 1000 - buyPrice * 1000) / 1000
            this.$set(item, 'discount_total_price', pref)
          })
          this.shoppingList = data
          this.getOrderCartCredit()
        }
      )
    },
    // 使用卡卷
    handieCouponChat(vo, item) {
      vo.coupon_id = item.id
      if (this.$util.isDef(item.ticket_id)) {
        vo.ticket_id = item.id
      } else {
        vo.ticket_id = 0
      }
      let buyPrice = 0
      if (item.coupon_type == 1) {
        buyPrice = floatCount(item.price)
      } else if (item.coupon_type == 2) {
        let price = vo.total_price
        let discount = item.discount
        buyPrice = floatCount(price - price * (discount / 10)).toFixed(2)
      }
      vo.best_coupon = item
      let pref = (vo.total_price * 1000 - buyPrice * 1000) / 1000
      this.$set(vo, 'discount_total_price', pref)
      this.$set(vo, 'discount_price', buyPrice)
      this.getOrderCartCredit()
    },
    // 不是使用卡卷
    noCoupon(vo) {
      vo.coupon_id = 0
      vo.ticket_id = 0
      this.$set(vo, 'discount_total_price', vo.total_price)
      this.$set(vo, 'discount_price', 0)
      this.getOrderCartCredit()
    },
    // 总价
    handieTotal() {
      let total = 0
      this.shoppingList.forEach(item => {
        total += floatCount(item.discount_total_price) || 0
      })
      total = (total * 1000 - this.credit_price * 1000) / 1000
      this.pay_price = floatCount(total)
    },
    // 优惠价格
    handieDiscount() {
      let price = 0
      this.shoppingList.forEach(item => {
        price += floatCount(item.discount_price) || 0
      })
      this.reduced_price = floatCount(price)
    },
    // 提交订单
    handiedingdan() {
      this.disabled = true
      let course_arr = this.shoppingList.map(item => {
        let query = {
          course_ids: item.course_list.map(subItem => subItem.id).toString()
        }
        if (item.ticket_id) {
          query = {
            ...query,
            ticket: item.coupon_id
          }
        } else {
          query = {
            ...query,
            coupon: item.coupon_id
          }
        }
        return query
      })
      let params = {
        from: projectSetting.globDeviceType,
        course: course_arr
      }
      if (!this.$util.isEmpty(this.credit_obj)) {
        params = {
          ...params,
          credit: JSON.stringify(this.credit_obj)
        }
      }
      this.disabled = false
      this.$api.createOrderCourseCart(
        params,
        res => {
          // 是否需要支付
          if (res.data.need_pay) {
            this.$router.push({
              path: '/buy/confirm'
            })
            this.changeOrderData({
              order_no: res.data.order_no,
              payment: res.data.payment,
              return_url: '/my/study/course'
            })
            this.$store.dispatch('projectSetting/setGlobCartNumber')
          } else {
            this.$message.success(res.msg)
            this.$router.replace({
              path: '/my/study/course'
            })
          }
        },
        error => {
          this.$message.error(error.msg)
          this.disabled = false
        }
      )
    },
    // 返回购物车
    handieReturn() {
      this.$router.push({
        path: '/buy/cart'
      })
    },
    // get机构对应的卡卷
    getCouponSchoolInfo(item) {
      this.handleLoading()
      this.couponSchoolList = []
      this.$api.getCouponSchoolUser(
        {
          mhm_id: item.mhm_id,
          group: 1,
          price: item.total_price
        },
        res => {
          this.couponSchoolList = res.data
        }
      )
    },
    handleLoading() {
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 1000)
    },
    // 积分抵扣
    changePoints(obj) {
      if (this.$util.isEmpty(obj)) {
        this.credit_price = 0
        this.credit_obj = {}
      } else {
        this.credit_price = obj.num
        this.credit_obj = obj
      }
      this.handieTotal()
      this.handieDiscount()
    },
    // 获取积分
    getOrderCartCredit() {
      const _this = this
      let list = _this.shoppingList.reduce((pre, cur) => pre.concat(cur.course_list), [])
      let ids = list.map(item => item.id)
      let cid = _this.shoppingList
        .map(item => (item.ticket_id ? '' : item.coupon_id))
        .filter(item => item)
      let tid = _this.shoppingList.map(item => item.ticket_id || '').filter(item => item)
      _this.$api.getOrderCartCredit(
        {
          course: ids.toString(),
          coupon: cid.toString(),
          ticket: tid.toString()
        },
        res => {
          const { data } = res
          _this.creditList = data
          _this.changePoints(data[0])
        },
        err => {
          this.changePoints()
        }
      )
    }
  }
}
</script>
<style lang="scss" scoped>
// 卡卷
.shopping-coupon-loading {
  width: 380px;
  min-height: 80px;
}
.scrollbar {
  height: 330px;
  ::v-deep .el-scrollbar__wrap {
    overflow-x: auto;
  }
}
.shopping-coupon-popover {
  padding-right: 10px;
  .card {
    width: 58px;
    height: 32px;
    font-size: 16px;
    font-weight: 700;
    color: #fff;
    line-height: 32px;
    text-align: center;
    background-size: 100% 100%;
    &.youhui {
      background-image: url('../../assets/images/public/manjian.png');
    }
    &.dazhe {
      background-image: url('../../assets/images/public/dazhe.png');
    }
  }
  .info {
    flex: 1;
    margin-right: 10px;
    margin-left: 10px;
    .name {
      color: $text-color-secondary;
      font-size: 13px;
      .mhm {
        @include edu-color-auxiliary;
      }
    }
    .time {
      font-size: 12px;
      color: $text-color-auxiliary;
    }
  }
}
.shopping-coupon-footer {
  padding-top: 12px;
}
.shopping {
  margin-top: 10px;
  padding-bottom: 20px;
  background-color: #fff;
  .shopping-header {
    .title {
      padding: 0 30px;
      height: 44px;
      .name {
        font-size: 16px;
        color: $text-color-import;
      }
      .return {
        font-size: 14px;
        color: $text-color-secondary;
      }
    }
    .navbar {
      padding: 0 65px;
      height: 44px;
      background-color: #f5f5f5;
      .name {
        text-align: right;
        font-size: 14px;
        color: $text-color-secondary;
        &:nth-child(1) {
          text-align: center;
        }
      }
    }
  }
  .shopping-list {
    padding: 0 30px;
    .shopping-mhm {
      margin-top: 20px;
      .mhm-header {
        height: 44px;
        .title {
          font-size: 14px;
          font-weight: 400;
          color: $text-color-import;
        }
        .coupon-title {
          margin-left: 20px;
          padding: 2px 5px;
          cursor: pointer;
          font-size: 12px;
          color: $text-color-price;
          border: 1px dashed $text-color-price;
        }
      }
      .mhm-case {
        border: 1px solid #dcdfe6;
        padding: 0 20px;
        .item + .item {
          border-top: 1px solid #dcdfe6;
        }
        .item {
          padding: 20px 15px 20px 0;
        }
        .img {
          width: 170px;
          height: 0;
          padding-top: 94px;
          border-radius: 4px;
          overflow: hidden;
          position: relative;
          .el-image {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
          }
        }
        .info {
          width: 330px;
          margin-left: 20px;
          padding-bottom: 15px;
          flex-direction: column;
          .name {
            font-size: 13px;
            color: $text-color-import;
            line-height: 18px;
            @include ellipsisLine(2);
          }
          .dec {
            font-size: 12px;
            color: $text-color-secondary;
            span + span {
              margin-left: 20px;
            }
            i {
              color: #f54030;
            }
          }
        }
        .end {
          flex: 1;
          align-self: flex-start;
        }
        .picrie {
          color: $text-color-price;
          font-size: 14px;
        }
        .delete {
          font-size: 14px;
          color: $text-color-secondary;
        }
      }
      .mhm-combined {
        height: 64px;
        padding: 0 20px;
        border: 1px solid #dcdfe6;
        border-top: 0;
        font-size: 14px;
        .name {
          color: $text-color-import;
        }
        .money {
          color: $text-color-price;
        }
        .discount {
          margin-right: 40px;
          color: $text-color-secondary;
        }
      }
    }
  }
  .shopping-column {
    padding: 0 30px;
    height: 48px;
    .combined {
      width: 140px;
      margin-right: 40px;
      .discount {
        font-size: 14px;
        color: $text-color-secondary;
      }
      .name {
        font-size: 13px;
        color: $text-color-secondary;
      }
      .money {
        font-size: 18px;
        color: $text-color-price;
      }
    }
  }
}
</style>
